#region (c) 2009 Abdullin.com and Contributors

// Copyright (c) 2009 Abdullin.com and Contributors
// Site: http://abdullin.com/ncouch
// This code is released under the terms of the new BSD licence

#endregion

using System;
using System.IO;
using System.Net;
using System.Net.Cache;
using Lokad.Quality;

namespace NCouch.Rest
{
	[Immutable]
	public sealed class RestClient : IRestClient
	{
		IRestResponse IRestClient.GetResponse(IRestRequest request)
		{
			try
			{
				var webRequest = (HttpWebRequest) WebRequest.Create(request.RequestUri);
				webRequest.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
				webRequest.Method = request.Method;
				webRequest.ContentType = request.ContentType;

				foreach (var header in request.Headers)
				{
					webRequest.Headers.Add(header.Name, header.Value);
				}

				request.Content.Apply(stream => WriteContent(webRequest, stream));
				return new RestResponse((HttpWebResponse) webRequest.GetResponse());
			}
			catch (WebException e)
			{
				if (e.Response == null)
					throw;
				// till I get to rewrite web requests to live without exceptions
				return new RestResponse((HttpWebResponse) e.Response);
			}
		}

		static void WriteContent(WebRequest request, Action<Stream> content)
		{
			using (var writer = request.GetRequestStream())
			{
				content(writer);
			}
		}
	}
}